﻿using System;
using System.Xml.Linq;

namespace SlamCms.Common
{
	public static class XmlExtensions
	{
		public static string GetAttribute(this XElement elem, string name, bool mandatory = false)
		{
			if (elem == null)
				throw new ArgumentNullException("elem");

			if (name == null)
				throw new ArgumentNullException("name");

			var attribute = elem.Attribute(name);
			if (attribute == null && mandatory)
				throw new Exception("There is no attibute {0} in node {1}".F(name, elem.Name));

			if (attribute == null)
				return string.Empty;

			return attribute.Value;
		}

		public static T GetAttribute<T>(this XElement elem, string name, T defaultValue)
		{
			if (elem == null)
				throw new ArgumentNullException("elem");

			if (name == null)
				throw new ArgumentNullException("name");

			var attribute = elem.Attribute(name);
			if (attribute == null)
				return defaultValue;

			return (T)Convert.ChangeType(attribute.Value, typeof(T));
		}
	}
}
